package com.hanock.sm.fork2d;

import android.graphics.Paint.Align;
import android.graphics.RectF;

public class Label extends Node {

	private String text;
	private RectF tempRect;
	private float fontSize;
	private Texture texture;
	private Texture oldTexture;
	private Align align;
	
	private boolean resize;
	
	
	public Label(String text, float fontSize) {
		this.text = text;
		this.fontSize = fontSize;
		
		align = Align.LEFT;
		
		tempRect = new RectF();
	}
	
	@Override
	protected void draw(Canvas canvas) {
		super.draw(canvas);
		
		if (text == null || fontSize <= 0)
			return;
		
		TextureManager textureManager = TextureManager.getInstance();
		
		if (oldTexture != null){
			textureManager.release(oldTexture);
			oldTexture = null;
		}
		
		if (texture == null || !textureManager.has(texture)){
			texture = textureManager.load(text, fontSize, align);
			
			if (texture == null)
				return;
			
			if (getWidth() == 0 || getHeight() == 0 || resize){
				setSize(texture.getImageWidth(), texture.getImageHeight());
				resize = false;
			}
			
			// to notify the newly created texture before drawn first
			return; 
		}
		
		getDesRect(tempRect);
		canvas.drawImage(null, tempRect, texture);
	}

	public String getText() {
		return text;
	}
	
	public void setText(String text) {
		setText(text, true);
	}
	
	public void setText(String text, boolean resize) {
		this.text = text;
		
		if (texture != null){
			oldTexture = texture;
			texture = null;
		}
		
		this.resize = resize;
	}
	
	public void setAlign(Align align) {
		this.align = align;
	}
}






















